package com.agileai.bpm.interceptor.flow;

import com.agileai.bpm.common.BPMConstants;
import com.agileai.bpm.common.VariableInterpreter;
import com.agileai.bpm.domain.define.Activity;
import com.agileai.bpm.domain.running.ActivityInstance;
import com.agileai.bpm.interceptor.BaseInterceptor;
import com.agileai.bpm.model.BizAttributeType;
import com.agileai.bpm.model.FlowLauncherType;
import com.agileai.bpm.model.InterceptorModelDocument.InterceptorModel;
import com.agileai.bpm.webservice.BPMService;
import com.agileai.bpm.webservice.BizAttribute;
import com.agileai.bpm.webservice.LaunchWorkItem;
import com.agileai.hotweb.common.BeanFactory;

public class ProcessLauncherInterceptor extends BaseInterceptor{
	private FlowLauncherType flowLauncherType;
	
	public ProcessLauncherInterceptor(InterceptorModel model,Activity activity){
		this.type = BaseInterceptor.Type.FlowLauncher;
		this.isSynchronous = model.getSynchronous();
		this.variableCode = model.getVariableCode();
		this.varExpression = model.getVarExpression();
		
		flowLauncherType = model.getFlowLauncher();
	}
	
	public void doIntercept(ActivityInstance activityInstance) throws Exception  {
		BPMService bpmService = (BPMService)BeanFactory.instance().getBean("bpmService");
		
		LaunchWorkItem launchWorkItem = new LaunchWorkItem();
		launchWorkItem.setUserCode(BPMConstants.SERVICE_USER_ID);
		String bizRecordIdExp = flowLauncherType.getBizRecordId(); 
		String bizRecordId = VariableInterpreter.replaceVariables(bizRecordIdExp, activityInstance);
		launchWorkItem.setBizRecordId(bizRecordId);
		String processId = bpmService.getCurrentProcessId(flowLauncherType.getProcessCode());
		launchWorkItem.setProcessId(processId);
		
		String processTitle = VariableInterpreter.replaceVariables(flowLauncherType.getProcessTitle(), activityInstance);
		launchWorkItem.setTitle(processTitle);
		
		if (flowLauncherType.getBizAttributeArray() != null){
			for (int i=0;i < flowLauncherType.getBizAttributeArray().length;i++){
				BizAttributeType bizAttributeType = flowLauncherType.getBizAttributeArray(i);
				BizAttribute bizAttribute = new BizAttribute();
				bizAttribute.setCode(bizAttributeType.getCode());
				String expression = bizAttributeType.getValue();
				String value = VariableInterpreter.replaceVariables(expression, activityInstance);
				bizAttribute.setValue(value);
				launchWorkItem.getAttributeList().add(bizAttribute);				
			}
		}
		bpmService.launchProcess(launchWorkItem,flowLauncherType.getSkipFirstManual());
	}
	
	public void handleException(ActivityInstance activityInstance,Exception ex) {
		ex.printStackTrace();
	}

}
